package server.business.task.data;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import server.ServerConfigCache;
import server.business.task.config.TaskConfig;
import server.commonData.User;
import server.commonData.db.TaskDb;
import server.commonData.db.TaskListDb;
import server.msgBean.LoginMessage.TaskListRes;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.ArrayListMultimap;

/**
 * 任务列表对象
 * @author King
 *
 */
public class TaskList
{
	/**任务列表集合**/
	private Map<Integer, Task> taskList = new HashMap<Integer, Task>();
	
	/**任务条件集合**/
	private ArrayListMultimap<Integer, Task> taskConditionMap = ArrayListMultimap.create();

	/**任务初始化**/
	public void init()
	{
		Collection<TaskConfig> tasks = ServerConfigCache.taskMap.values();
		for(TaskConfig config:tasks)
		{
			Task task = new Task(config.taskId);
			taskConditionMap.put(config.conditionType, task);
			taskList.put(config.taskId, task);
		}
	}
	

	public ArrayListMultimap<Integer, Task> getTaskConditionMap() {
		return taskConditionMap;
	}
	
	/**发给客户端的信息**/
	public TaskListRes.Builder showClient(User user)
	{
		TaskListRes.Builder builder = TaskListRes.newBuilder();
		for(Task task:taskList.values())
		{
			if(task.isAward())
				continue;
			builder.addTaskInfo(task.showToClient(user));
		}
		return builder;
	}

	public Map<Integer, Task> getTaskList() {
		return taskList;
	}
	
	/**存库**/
	public String toDb()
	{
		TaskListDb db = new TaskListDb();
		for(Task task:taskList.values())
		{
			db.taskList.add(task.toDb());
		}
		return JSONArray.toJSONString(db);
	}
	
	/**读库**/
	public void fromDb(String db)
	{
		TaskListDb taskList = JSONArray.parseObject(db, TaskListDb.class);
		if(taskList==null)
			return;
		for(TaskDb taskDb:taskList.taskList)
		{
			Task task = this.taskList.get(taskDb.taskId);
			if(task==null)
				continue;
			task.fromDb(taskDb);
		}
	}
}
